﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;
using System.Globalization;
using MyGeneration.dOOdads;
using System.IO;

namespace MobileShop
{
    public partial class Checkout : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            divShow.Visible = BasePage.TotalQuantity > 0;
            lblNoItems.Visible = BasePage.TotalQuantity <= 0;
            if (!IsPostBack)
            {
                btnHidCheckOut.PostBackUrl = POSSystem.BLL.Utilities.GetConfigAppSetting("PayPalURL").ToString();
                PageMap = string.Format("Cart[{0}]|Checkout[{1}]", this.ResolveUrl("~/Cart.aspx"), this.ResolveUrl("~/Checkout.aspx"));
                if (View_Customers.GetCurrentUser() != null)
                {
                    txtEmail.Text = View_Customers.GetCurrentUser().s_Email;
                    txtAddress.Text = View_Customers.GetCurrentUser().s_Address;
                    txtPhone.Text = View_Customers.GetCurrentUser().s_Phone;
                    txtName.Text = View_Customers.GetCurrentUser().s_CustomerName;
                    txtShipTo.Text = txtAddress.Text;
                }

                TotalAmt = BasePage.TotalAmount;
                ShippingCost = SystemVariables.SysVars.ShippingCost / 2 * (TotalQuantity + 1);
                UpdateCost();
            }
        }

        public bool UsePayPal()
        {
            return View_Customers.GetCurrentUser() == null || View_Customers.GetCurrentUser().RowCount <= 0 || View_Customers.GetCurrentUser().Price == CustomerType.CustomerPrice.SalePrice;
        }

        public int OrderKey
        {
            get;
            set;
        }

        public string GetThankYouURL()
        {
            return string.Format("{0}", POSSystem.BLL.Utilities.GetConfigAppSetting("ThankYou"), OrderKey);
        }

        protected void btnApply_OnClick(object sender, EventArgs e)
        {
            lblError.Text = "";
            if (txtVoucherCode.Text == "")
                return;

            View_Vouchers vc = View_Vouchers.GetByCode(txtVoucherCode.Text);
            if (vc.RowCount <= 0)
            {
                txtVoucherCode.Text = "";
                lblError.Text = "Invalid Voucher Code!";
            }

            if (!vc.Active)
            {
                txtVoucherCode.Text = "";
                lblError.Text = "'Voucher Code disabled!";
                return;
            }

            if (vc.IsUsed)
            {
                txtVoucherCode.Text = "";
                lblError.Text = "'Voucher Code has been used!";
                return;
            }

            decimal s = 0;

            if (!vc.MultiCheckOut)
            {
                POSSystem.BLL.CustomerOrders order = POSSystem.BLL.CustomerOrders.GetPendingOrdersByVoucherId(vc.ID);
                if (order.RowCount > 0)
                {
                    txtVoucherCode.Text = "";
                    lblError.Text = "'Voucher Code has been used!";
                    return;
                }
            }
            else if (vc.s_DiscountAmount != "" && vc.s_Balance != "")
            {
                POSSystem.BLL.CustomerOrders order = POSSystem.BLL.CustomerOrders.GetPendingOrdersByVoucherId(vc.ID);

                for (int i = 0; i < order.RowCount; i++)
                {
                    s += order.TotalAmount;
                    order.MoveNext();
                }

                if (s > vc.Balance || vc.Balance == 0)
                {
                    txtVoucherCode.Text = "";
                    lblError.Text = "Balance exceeded!";
                    return;
                }
            }

            if (vc.IsExpired())
            {
                txtVoucherCode.Text = "";
                lblError.Text = "Voucher code expired!";
                return;
            }

            UpdateCost();
        }

        protected void btnCheckout_OnClick(object sender, EventArgs e)
        {
            if (Cart.SelectedItems.RowCount <= 0)
            {
                lblError.Text = "Nothing to purchase.";
                return;
            }
            else
                lblError.Text = "";

            TransactionMgr tx = TransactionMgr.ThreadTransactionMgr();
            try
            {
                tx.BeginTransaction();

                CustomerOrders order = new CustomerOrders();
                order.AddNew();
                order.CreatedDate = DateTime.UtcNow.AddHours(SystemVariables.SysVars.TimeZone);
                order.PreferredShipDate = DateTime.UtcNow.AddHours(SystemVariables.SysVars.TimeZone);
                Sequence seq = new Sequence();
                order.OrderNo = seq.GetNewID("CustomerOrders");
                order.CustomerAddress = txtAddress.Text;
                order.ShipAddress = txtShipTo.Text;
                order.s_CustomerID = View_Customers.GetCurrentUser() != null && View_Customers.GetCurrentUser().RowCount > 0 ? View_Customers.GetCurrentUser().s_ID : "";
                order.s_CustomerName = txtName.Text;
                order.s_CustomerPhone = txtPhone.Text;
                order.Deleted = false;
                order.s_LastModifiedByCustomer = order.s_CustomerID;
                order.GST = TotalAmt - DiscountAmt + ShippingCost;
                order.TotalAmount = TotalAmt - DiscountAmt + ShippingCost;
                order.StatusID = OrderStatus.Pending;
                order.PaymentMethodID = UsePayPal() ? PaymentMethod.PayPal : PaymentMethod.BankTransfer;
                order.BranchID = Branches.CurrentBranchID;

                if (txtVoucherCode.Text.Trim() != "" && !UsePayPal())
                {
                    string code = txtVoucherCode.Text.Trim();
                    View_Vouchers vc = View_Vouchers.GetByCode(code);
                    if (vc.RowCount >= 0 && vc.Active && !vc.IsUsed && !vc.IsExpired() && (vc.s_Balance == "" || vc.Balance > 0))
                    {
                        order.VoucherID = vc.ID;
                    }
                    else
                        throw new ApplicationException("Invalid Voucher Code or Balance Exceed!");
                }
                else if (txtVoucherCode.Text.Trim() != "")
                {
                    if (DiscountAmt == order.TotalAmount)
                        order.StatusID = OrderStatus.Pending;
                }

                order.Save();

                OrderKey = order.ID;

                OrderItems items = BasePage.SelectedItems;
                items.Rewind();
                for (int i = 0; i < items.RowCount; i++)
                {
                    items.OrderID = order.ID;
                    items.s_LastModifiedByCustomer = order.s_LastModifiedByCustomer;
                    items.s_LastModifiedDate = order.s_LastModifiedDate;
                    items.Deleted = false;
                    items.MoveNext();
                }

                items.Save();

                tx.CommitTransaction();

                decimal shippingCost = SystemVariables.SysVars.ShippingCost / 2 * (TotalQuantity + 1);
                
                BasePage.SelectedItems = new OrderItems();

                try
                {
                    string tempFile = Server.MapPath("~/MailTemplates/NewOrder.htm");
                    string content = File.ReadAllText(tempFile);
                    content = string.Format(content, order.s_CustomerName, order.s_ShipAddress, order.s_CustomerPhone);
                    string recipients = POSSystem.BLL.Utilities.GetConfigAppSetting("AutoMailRecipients");
                    POSSystem.BLL.Utilities.SendEmail(recipients, "New Customer Order", content);
                }
                catch (Exception ex)
                {
                    ErrorLog.WriteToFile("New Customer Order", ex.Message, ex.StackTrace);
                }

                if (DiscountAmt < order.TotalAmount && UsePayPal())
                {
                    btnCheckout.Enabled = false;
                    ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), string.Format("checkout({0}, {1});", OrderKey, shippingCost), true);
                }
                else
                    lblNote.Visible = true;
            }
            catch (Exception ex)
            {
                tx.RollbackTransaction();
                ErrorLog.WriteToFile("Order.aspx.cs", "lnkSubmit_OnClick", ex.StackTrace);
                ErrorLog.WriteToFile("Order.aspx.cs", "lnkSubmit_OnClick", ex.Message);
            }
        }

        public Decimal TotalAmt
        {
            get
            {
                if (ViewState["CartTotalAmount"] == null || !(ViewState["CartTotalAmount"] is Decimal))
                    ViewState["CartTotalAmount"] = (Decimal)0;
                return Decimal.Parse(ViewState["CartTotalAmount"].ToString(), CultureInfo.InvariantCulture);
            }
            set { ViewState["CartTotalAmount"] = value; lblItemAmount.Text = string.Format("{0:C}", value); }
        }

        public Decimal DiscountAmt
        {
            get
            {
                if (ViewState["DiscountAmt"] == null || !(ViewState["DiscountAmt"] is Decimal))
                    ViewState["DiscountAmt"] = (Decimal)0;
                return Decimal.Parse(ViewState["DiscountAmt"].ToString(), CultureInfo.InvariantCulture);
            }
            set { ViewState["DiscountAmt"] = value; lblDiscount.Text = string.Format("{0:C}", value); }
        }

        public Decimal ShippingCost
        {
            get
            {
                if (ViewState["ShippingCost"] == null || !(ViewState["ShippingCost"] is Decimal))
                    ViewState["ShippingCost"] = (Decimal)0;
                return Decimal.Parse(ViewState["ShippingCost"].ToString(), CultureInfo.InvariantCulture);
            }
            set { ViewState["ShippingCost"] = value; lblShippingCost.Text = string.Format("{0:C}", value); }
        }

        private void UpdateCost()
        {
            if (txtVoucherCode.Text == "")
                DiscountAmt = 0;
            else
            {
                View_Vouchers vc = View_Vouchers.GetByCode(txtVoucherCode.Text);
                if (vc.RowCount == 0)
                    DiscountAmt = 0;
                else if (vc.s_DiscountAmount != "")
                    DiscountAmt = vc.DiscountAmount;
                else
                    DiscountAmt = TotalAmt * vc.DiscountPercent / 100;
            }

            lblTotalAmt.Text = string.Format("{0:C}", TotalAmt - DiscountAmt + ShippingCost);

            if (TotalQuantity > 0)
            {
                decimal tmpDiscount = DiscountAmt / TotalQuantity;
                string html = "";
                BasePage.SelectedItems.Filter = "";
                BasePage.SelectedItems.Rewind();
                for (int i = 0; i < BasePage.SelectedItems.RowCount; i++)
                {
                    decimal unitPrice = Math.Round(BasePage.SelectedItems.CustomerPrice - tmpDiscount, 2);

                    html += string.Format("<input type='hidden' name='item_number_{0}' value='{1}' />", i + 1, BasePage.SelectedItems.BarCode);
                    html += string.Format("<input type='hidden' name='item_name_{0}' value='{1}' />", i + 1, BasePage.SelectedItems.ProductName);
                    html += string.Format("<input type='hidden' name='quantity_{0}' value='{1}' />", i + 1, BasePage.SelectedItems.Quantity);
                    html += string.Format("<input type='hidden' name='amount_{0}' value='{1}' />", i + 1, unitPrice);
                    BasePage.SelectedItems.MoveNext();
                }
                litItem.Text = html;
            }
        }

    }
}